package com.io.bio;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 *  BIO：阻塞、同步
 *  BIO通讯方式很依赖于网络，若网速不好，阻塞时间会很长。每次请求都由程序执行并返回，这是同步的缺陷。
 *  BIO工作流程：
 *  1 server端服务器启动
 *  2 server端服务器阻塞监听client请求
 *  3 server端服务器接收请求，创建线程实现任务
 */
public class BIOServer {
    // 服务器对外的端口号
    private static final int PORT = 8888;

    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        ExecutorService executorService = null;
        try {
            serverSocket = new ServerSocket(PORT);
            System.out.println("BIO Server start...");
            /*----------------------传统的新增线程--------------------------*/
//            while (true) {
//                // 服务器监听：阻塞，等待Client请求
//                socket = serverSocket.accept();
//                System.out.println("Server 服务器确认请求：" + socket);
//                new Thread(new BIOServerHandler(socket)).start();
//            }
            /*------------通过线程池处理缓解高并发给程序带来的压力（伪异步IO编程）------------*/
            executorService = new ThreadPoolExecutor(10, 100, 1000, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(50));
            while (true) {
                socket = serverSocket.accept();
                executorService.execute(new BIOServerHandler(socket));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {

        } finally {
            try {
                if (socket != null) {
                    socket.close();
                    socket = null;
                }
                if (serverSocket != null) {
                    serverSocket.close();
                    serverSocket = null;
                    System.out.println("BIO Server close...");
                }
                executorService.shutdown();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
